/********************************************************************
	Rhapsody	: 7.5 
	Login		: KBE
	Component	: DefaultComponent 
	Configuration 	: CodeConfig
	Model Element	: ThreadPool
//!	Generated Date	: Tue, 25, Sep 2012  
	File Path	: DefaultComponent\CodeConfig\ThreadPool.cpp
*********************************************************************/

//## auto_generated
#include "ThreadPool.h"
//## operation ThreadPool(Reactor*)
#include "Reactor.h"
//## package Default

//## class ThreadPool
ThreadPool::ThreadPool(Reactor* reactor) {
    itsReactor = NULL;
    //#[ operation ThreadPool(Reactor*)
    itsReactor = reactor;
	mutex_ = new Thread_Mutex();
	leader_thread_ = 0;
    //#]
}

ThreadPool::ThreadPool() {
    itsReactor = NULL;
}

ThreadPool::~ThreadPool() {
	delete mutex_;
    cleanUpRelations();
}

void ThreadPool::deactivateHandle(HANDLE h, Event_Type& et) {
    //#[ operation deactivateHandle(HANDLE,Event_Type)
    itsReactor->deactivateHandle(h, et);
    //#]
}

void ThreadPool::join(int timeout) {
    //#[ operation join(int)
    for ( ; ; )
    {
		mutex_->wait(); // Threads waits to obtain the leader role
    	leader_thread_ = Thread_Manager::self(); // Assume the leader role
		//printf(">>>leader %d\n", leader_thread_);

    	// After becoming the leader,
    	// the tread uses the reactor to wait for events
    	itsReactor->handleEvents(timeout);
    }
    //#]
}

void ThreadPool::promoteNewLeader() {
    //#[ operation promoteNewLeader()
    if (leader_thread_ != Thread_Manager::self())
		// Exception: only leader can promote !
    	printf("LEADER %d self %d\n", leader_thread_, Thread_Manager::self());
	else
	{
		// indicate that we are no longer the leader
		//printf("<<<leader %d\n", leader_thread_);
		leader_thread_= NULL;
		mutex_->signal(); // Release mutex_ for next leader thread
	}
    //#]
}

void ThreadPool::reactivateHandle(HANDLE h, Event_Type& et) {
    //#[ operation reactivateHandle(HANDLE,Event_Type)
    itsReactor->reactivateHandle(h, et);
    //#]
}

Reactor* ThreadPool::getItsReactor() const {
    return itsReactor;
}

void ThreadPool::cleanUpRelations() {
    if(itsReactor != NULL)
        {
            itsReactor = NULL;
        }
}

/*********************************************************************
	File Path	: DefaultComponent\CodeConfig\ThreadPool.cpp
*********************************************************************/
